package com.tusuo.stds.ui.main;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baoyz.swipemenulistview.SwipeMenu;
import com.baoyz.swipemenulistview.SwipeMenuCreator;
import com.baoyz.swipemenulistview.SwipeMenuItem;
import com.baoyz.swipemenulistview.SwipeMenuListView;
import com.tusuo.stds.MyApp;
import com.tusuo.stds.R;
import com.tusuo.stds.biz.PageStatus;
import com.tusuo.stds.di.DaggerScope;
import com.tusuo.stds.di.Injector;
import com.tusuo.stds.rest.ApiHelper;
import com.tusuo.stds.rest.ApiResult;
import com.tusuo.stds.rest.SceneList;
import com.tusuo.stds.ui.BaseToolbarFragment;
import com.tusuo.stds.ui.ToolbarOwner;
import com.tusuo.stds.ui.scene.SceneActivity_;
import com.tusuo.stds.ui.scenedetail.SceneDetailActivity_;
import com.tusuo.stds.ui.scenesetting.SceneSettingActivity_;
import com.tusuo.stds.util.Utils;

import org.androidannotations.annotations.AfterInject;
import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.ItemClick;
import org.androidannotations.annotations.ViewById;
import org.androidannotations.annotations.res.StringRes;
import org.parceler.Parcels;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;

import autodagger.AutoComponent;
import autodagger.AutoInjector;
import rx.Subscriber;
import rx.functions.Action0;
import timber.log.Timber;

/**
 * @author J.Huang
 * @version 1.0
 *
 */
@AutoComponent(
        dependencies = MyApp.class
)
@AutoInjector
@DaggerScope(ChallengeFragment.class)
@EFragment(R.layout.frag_challenge)
public class ChallengeFragment extends BaseToolbarFragment {

    @Inject
    ApiHelper mApiHelper;
    @Inject
    SharedPreferences mSharedPref;

    @ViewById(R.id.list_scene)
    SwipeMenuListView listView;


    @StringRes(R.string.toolbar_title_challenge)
    String toolbarTitle;
    @StringRes(R.string.err_msg_server)
    String mErrMsgServer;

    private SceneList mSceneList = null;

    private Subscriber<SceneList> mGetSceneListSubscriber = null;
    private SceneListAdapter adapter;
    ArrayList<SceneList.Scene> mData;

    @AfterInject
    void initDI() {

        Injector.initChallengeFragmentComponent().inject(this);
    }

    @AfterViews
    void init() {
        List<ToolbarOwner.MenuAction> menuActionList = new ArrayList<>();
        ToolbarOwner.MenuAction menuAction = new ToolbarOwner.MenuAction("", new Action0() {
            @Override
            public void call() {
                Intent intent = new Intent();
                intent.setClass(getActivity(), SceneSettingActivity_.class);
                startActivity(intent);
            }
        }, R.drawable.st_confirm_btn_screening);

        menuActionList.add(menuAction);

        PageStatus pageStatus = new PageStatus(true, false, toolbarTitle);
        initData(pageStatus,menuActionList);

        initListView();

    }

    private void initListView() {
        SwipeMenuCreator creator = new SwipeMenuCreator() {

            @Override
            public void create(SwipeMenu menu) {
                // create "delete" item
                SwipeMenuItem deleteItem = new SwipeMenuItem(
                        getActivity().getApplicationContext());
                // set item background
                deleteItem.setBackground(R.drawable.hidden);
                // set item width
                deleteItem.setWidth(Utils.dp2px(130,getContext()));
                // set a icon
//                deleteItem.setIcon(R.drawable.about_img_logo);
                // add to menu
                menu.addMenuItem(deleteItem);
            }
        };
        listView.setMenuCreator(creator);
        listView.setOnMenuItemClickListener(new SwipeMenuListView.OnMenuItemClickListener() {
            @Override
            public boolean onMenuItemClick(final int position, SwipeMenu menu, int index) {
                switch (index) {
                    case 0:
                        sceneHidden(mData.get(position).Id,position);
                        break;
                }
                // false : close the menu; true : not close the menu
                return false;
            }
        });
        listView.setSwipeDirection(SwipeMenuListView.DIRECTION_LEFT);

    }

    void sceneHidden(int sceneId,int position) {
        mApiHelper.setSceneHidden(new SceneHiddenSubscriber(position),sceneId,true);
    }

    private ArrayList<SceneList.Scene> sceneSort(SceneList list) {

        ArrayList<SceneList.Scene> tempData = new ArrayList<>();
        for (SceneList.Scene scene : list.Data) {
            if (!scene.IsHidden) {
                tempData.add(scene);
            }
        }


        return tempData;
    }

    private boolean checkData(ArrayList<SceneList.Scene> tempData) {
        for (int i = 0; i < tempData.size(); i ++) {
            if (tempData.get(i).Id != mData.get(i).Id) {
                return false;
            }
        }

        return true;

    }

    @Override
    public void onResume() {
        super.onResume();

        mGetSceneListSubscriber = new GetSceneListSubscriber();
        mApiHelper.getSceneList(mGetSceneListSubscriber,1,"");
    }

    @Override
    public void onPause() {
        if (mGetSceneListSubscriber != null) {
            mGetSceneListSubscriber.unsubscribe();
            mGetSceneListSubscriber = null;
        }
        super.onPause();
    }

    @Override
    protected void findViews() {
        mToolbar = (Toolbar) getActivity().findViewById(R.id.challenge_toolbar);
        mToolbarTitle = (TextView) getActivity().findViewById(R.id.challenge_tv_toolbar_title);
    }

    @ItemClick(R.id.list_scene)
    void listItemClicked(SceneList.Scene scene) {
        if (Utils.UI.isFastDoubleClick()) {
            return;
        }

        Intent intent = new Intent();
        intent.putExtra(SceneList.Scene.EXTRA_NAME, Parcels.wrap(scene));

        if (scene.LockStatus == 0) {
            intent.setClass(getContext(), SceneDetailActivity_.class);
        }else {
            intent.setClass(getContext(), SceneActivity_.class);
        }

        getContext().startActivity(intent);
    }

    private class SceneHiddenSubscriber extends Subscriber<ApiResult> {
        private int mPosition;

        SceneHiddenSubscriber(int position) {
            mPosition = position;
        }


        @Override
        public void onCompleted() {


        }

        @Override
        public void onError(Throwable e) {
            System.out.println(e);
        }

        @Override
        public void onNext(ApiResult apiResult) {
            mData.remove(mPosition);
            adapter.notifyDataSetChanged();
        }
    }

    private class GetSceneListSubscriber extends Subscriber<SceneList> {
        @Override
        public void onCompleted() {}

        @Override
        public void onError(Throwable e) {
            Timber.d(e.toString());
            Utils.UI.showToastShort(mErrMsgServer);
        }

        @Override
        public void onNext(SceneList list) {
            ArrayList<SceneList.Scene> tempData = sceneSort(list);

            if (list.checkState(getContext())) {
                if (list.Total < 1 || list.Data.size() < 1) {

                } else {
                    if (mData == null || mData.size() != tempData.size() || !checkData(tempData)) {
                        mData = tempData;

                        adapter = new SceneListAdapter(getContext(), mData);
                        listView.setAdapter(adapter);
                    }
                }
            }
        }
    }

}
